package com.asion.qkan.adapter;

import android.content.Context;
import android.support.v4.util.Pools;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.asion.qkan.entry.RecommendEntry;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by gino on 16-10-14.
 */

public class RecViewpagerAdapter extends PagerAdapter {
    private Context context;
    private OnViewpagerItemListener onViewpagerItemListener;
    private List<RecommendEntry.DataBean.TopicsBean> list;
    private Pools.Pool<SimpleDraweeView> pool= new Pools.SimplePool<>(4);

    public RecViewpagerAdapter(Context context, List<RecommendEntry.DataBean.TopicsBean> list) {
        this.context = context;
        this.list = new ArrayList<>(list);
        RecommendEntry.DataBean.TopicsBean first = this.list.get(0);
        RecommendEntry.DataBean.TopicsBean last = this.list.get(list.size()-1);
        this.list.add(0,last);
        this.list.add(first);

    }

    @Override
    public int getCount() {
        return list.size();
    }


    public void setOnViewpagerItemListener(OnViewpagerItemListener onViewpagerItemListener){
        this.onViewpagerItemListener = onViewpagerItemListener;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        SimpleDraweeView imageView = pool.acquire();
        if (imageView == null) {
            imageView = new SimpleDraweeView(context);
        }
        imageView.setImageURI(list.get(position).getCover_image_url());
        RecommendEntry.DataBean.TopicsBean bean = list.get(position);
        imageView.setOnClickListener(v -> onViewpagerItemListener.OnviewpagerItemListener(bean));
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        pool.release((SimpleDraweeView) object);
    }
    public interface OnViewpagerItemListener{
        void OnviewpagerItemListener(RecommendEntry.DataBean.TopicsBean bean );
    }
}
